package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 插入订单表
        Order order = new Order();
        // 这里后续用发号器做（发号器也叫全局ID生成器）??
        // String orderId = UUID.randomUUID().toString();
        String orderId = globalIdGeneratorUtil.getNextSeq(OrderConstants.ORDER_ID, OrderConstants.INCRBY);
        order.setOrderId(orderId);
        order.setPayment(createOrderContext.getOrderTotal());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getBuyerNickName());

        int effectedRows1 = orderMapper.insert(order);
        if (effectedRows1 < 1) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }


        // 插入订单商品关联表

        ArrayList<Long> buyProjectIds = new ArrayList<>();

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {

            OrderItem orderItem = new OrderItem();
            // 这里后续用发号器做（发号器也叫全局ID生成器）??
            // String orderItemId = UUID.randomUUID().toString();
            String orderItemId = globalIdGeneratorUtil.getNextSeq(OrderConstants.ORDER_ITEM_ID, OrderConstants.INCRBY);
            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPicPath(cartProductDto.getProductImg());
            BigDecimal total = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            orderItem.setTotalFee(total.doubleValue());
            // 已锁定库存
            orderItem.setStatus(1);

            buyProjectIds.add(cartProductDto.getProductId());

            // 补充异常处理机制  ？？
            // 比如这个没有插入成功怎么办
            int effectedRows2 = orderItemMapper.insert(orderItem);
            if (effectedRows2 < 1) {
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                        OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }
        }

        createOrderContext.setOrderId(orderId);
        createOrderContext.setBuyProductIds(buyProjectIds);

        return true;
    }

}
